package com.paschino.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.paschino.bean.AccountBean;
import com.paschino.bean.AlbumBean;
import com.paschino.bean.CategoryBean;
import com.paschino.bean.ImageBean;
import com.paschino.bean.NewsBean;
import com.paschino.bean.ProductBean;
import com.paschino.modal.Album;
import com.paschino.modal.Category;
import com.paschino.modal.News;
import com.paschino.modal.Product;
import com.paschino.modal.StoreImage;
import com.paschino.modal.User;
import com.paschino.service.AlbumService;
import com.paschino.service.CategoryService;
import com.paschino.service.ImageService;
import com.paschino.service.NewsService;
import com.paschino.service.ProductService;
import com.paschino.service.UserService;
import com.paschino.utils.Constants;
import com.paschino.utils.FileUpload;
import com.paschino.utils.Formater;
import com.paschino.utils.MD5;

@Controller
public class AdminController {
	@Autowired
	ServletContext servletContext;

	@Autowired
	CategoryService categoryService;

	@Autowired
	ImageService imageService;

	@Autowired
	ProductService productService;

	@Autowired
	NewsService newsService;

	@Autowired
	UserService userService;

	@Autowired
	AlbumService albumService;

	private String userName;

	@RequestMapping(value = "/admin/addAccount")
	public ModelAndView showAddAccountPage() {
		ModelAndView mv = new ModelAndView("addAccount");
		return mv;
	}

	@RequestMapping(value = "/admin/listAccount")
	public ModelAndView showListAccountPage() {
		ModelAndView mv = new ModelAndView("listAccount");
		return mv;
	}

	@RequestMapping(value = "/admin/updateAccount")
	public ModelAndView showUpdateAccountPage() {
		ModelAndView mv = new ModelAndView("updateAccount");
		return mv;
	}

	@RequestMapping(value = "/admin/getChangePassword")
	public ModelAndView showchangePasswordPage(
			@ModelAttribute("account") AccountBean accountBean) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("account", new AccountBean());
		ModelAndView mv = new ModelAndView("changePassword", model);
		return mv;
	}

	@RequestMapping(value = "/admin/changePassword", method = RequestMethod.POST)
	public ModelAndView changePassword(
			@ModelAttribute("account") AccountBean accountBean) {
		Map<String, Object> model = new HashMap<String, Object>();
		if (processChangePassword(accountBean)) {
			model.put("message", "Success");
		} else {
			model.put("message", "Fail");
		}
		ModelAndView mv = new ModelAndView("redirect:/admin/getChangePassword",
				model);
		return mv;
	}

	@RequestMapping(value = "/admin/uploadFile", method = RequestMethod.POST)
	public @ResponseBody
	void uploadFile(MultipartHttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> message = new HashMap<String, String>();
		String filelocation = "";
		Album album = new Album();
		try {
			MultipartFile imagefile = request.getFile("imgFile");
			if (!imagefile.isEmpty()) {
				String location = servletContext.getRealPath("/");
				if (processAddImage(imagefile, location,
						Constants.NEWS_IMAGE_FOLDER)) {
					if (processSaveImage(imagefile, Constants.NEWS, album)) {
						filelocation = File.separator + "resources"
								+ File.separator + Constants.NEWS_IMAGE_FOLDER
								+ File.separator
								+ imagefile.getOriginalFilename();
					}
				}
			} else {
				filelocation = "Upload Failed";
			}
		} catch (FileUploadException e) {
			message.put("error", e.getMessage());
		} catch (Exception ex) {
			message.put("error", ex.getMessage());
			filelocation = "Upload Failed";
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().print(filelocation);

	}

	@RequestMapping(value = "/admin/listCategory", method = RequestMethod.GET)
	public ModelAndView showListCategoryPage() {

		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		userName = auth.getName();
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("categoryList",
				prepareCategoryList(categoryService.getCategorieList()));
		ModelAndView mv = new ModelAndView("listCategory", model);
		return mv;
	}

	@RequestMapping(value = "/admin/getAddCategory", method = RequestMethod.GET)
	public ModelAndView showAddCategoryPage(
			@ModelAttribute("category") CategoryBean categoryBean) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("category", new CategoryBean());
		ModelAndView mv = new ModelAndView("addCategory", model);
		return mv;
	}

	@RequestMapping(value = "/admin/addCategory", method = RequestMethod.POST)
	public ModelAndView addNewCategory(
			@ModelAttribute("category") CategoryBean categoryBean) {
		ModelAndView mv = new ModelAndView("redirect:/admin/listCategory");
		if (!categoryService.addCategory(prepareCategory(categoryBean))) {
			mv = new ModelAndView("redirect:/admin/getAddCategory");
		}
		return mv;
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/deleteCategory", method = RequestMethod.GET)
	public ModelAndView deleteCategory(HttpServletRequest request,
			HttpServletResponse response) {
		int categoryID = Integer.parseInt(request.getParameter("CategoryID"));
		Map<String, Object> model = new HashMap<String, Object>();
		Category cate = categoryService.getCategory(categoryID);
		List<Product> productList = productService.getProductListByCate(cate);
		for (Product product : productList) {
			int deleteProductofCate = productService.deleteProduct(product
					.getId());
		}
		int deleteCate = categoryService.deleteCategory(categoryID);
		model.put("categoryList",
				prepareCategoryList(categoryService.getCategorieList()));
		ModelAndView mv = new ModelAndView("listCategory", model);
		return mv;
	}

	@RequestMapping(value = "/admin/getUpdateCategory", method = RequestMethod.GET)
	public ModelAndView showUpdateCategoryPage(
			@RequestParam("cateId") String cateId,
			@ModelAttribute("category") CategoryBean categoryBean) {
		categoryBean = prepareCategoryBean(cateId);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("category", categoryBean);
		ModelAndView mv = new ModelAndView("updateCategory", model);
		return mv;
	}

	@RequestMapping(value = "/admin/updateCategory", method = RequestMethod.POST)
	public ModelAndView updateCategory(
			@ModelAttribute("category") CategoryBean categoryBean) {
		ModelAndView mv = new ModelAndView("redirect:/admin/listCategory");
		if (!categoryService
				.updateCategory(prepareUpdateCategory(categoryBean))) {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("category", categoryBean);
			mv = new ModelAndView("redirect:/admin/getUpdateCategory", model);
		}

		return mv;
	}

	@RequestMapping(value = "/admin/getAddProduct", method = RequestMethod.GET)
	public ModelAndView showAddProductPage(
			@ModelAttribute("product") ProductBean productBean) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("categoryList",
				prepareCategoryList(categoryService.getCategoryListByActive()));
		ModelAndView mv = new ModelAndView("addProduct", model);
		return mv;
	}

	@RequestMapping(value = "/admin/addProduct", method = RequestMethod.POST)
	public ModelAndView addNewProduct(
			@ModelAttribute("product") ProductBean productBean) {
		ModelAndView mv = new ModelAndView();
		if (null != categoryService.getCategory(productBean.getCategoryId())) {
			if (processAddProduct(productBean)) {
				mv = new ModelAndView("redirect:/admin/listProduct");
			}
		} else {
			Map<String, String> message = new HashMap<String, String>();
			message.put("error", "Please select Category");
			mv = new ModelAndView("redirect:/admin/getAddProduct", message);
		}

		return mv;
	}

	@RequestMapping(value = "/admin/getUpdateProduct", method = RequestMethod.GET)
	public ModelAndView showUpdateProductPage(
			@RequestParam("productId") String productId,
			@ModelAttribute("product") ProductBean productBean) {
		productBean = prepareProductBean(productId);
		List<CategoryBean> cateList = prepareCategoryList(categoryService
				.getCategoryListByActive());
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("categoryListUpdate", cateList);
		model.put("product", productBean);
		ModelAndView mv = new ModelAndView("updateProduct", model);
		return mv;
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/deleteProduct", method = RequestMethod.GET)
	public ModelAndView deleteProduct(HttpServletRequest request,
			HttpServletResponse response) {
		int productID = Integer.parseInt(request.getParameter("ProductID"));
		Map<String, Object> model = new HashMap<String, Object>();
		Product product = productService.getProduct(productID);
		Category cate = categoryService.getCategory(product.getCategoryId()
				.getId());
		int deleteProduct = productService.deleteProduct(productID);
		List<Product> productList = prepareLisProductBean(cate);
		model.put("productList", productList);
		model.put("chooseCate", cate);
		model.put("cateList", categoryService.getCategoryListByActive());
		ModelAndView mv = new ModelAndView("listProduct", model);
		return mv;
	}

	@RequestMapping(value = "/admin/updateProduct", method = RequestMethod.POST)
	public ModelAndView updateProduct(
			@ModelAttribute("product") ProductBean productBean) {
		ModelAndView mv = new ModelAndView();
		if (productService.updateProduct(prepareUpdateProduct(productBean))) {
			mv = new ModelAndView("redirect:/admin/listProduct");
		} else {
			Map<String, String> message = new HashMap<String, String>();
			message.put("error", "fail");
			mv = new ModelAndView("redirect:/admin/getUpdateProduct", message);
		}
		return mv;
	}

	@RequestMapping(value = "/admin/getCateList", method = RequestMethod.GET)
	public ModelAndView getCateList(HttpServletRequest request,
			HttpServletResponse response) {
		int cateID = Integer.parseInt(request.getParameter("cateID"));
		Map<String, Object> model = new HashMap<String, Object>();
		List<Product> productList = new ArrayList<Product>();
		Category cate = categoryService.getCategory(cateID);
		productList = prepareLisProductBean(cate);
		model.put("productList", productList);
		model.put("chooseCate", cate);
		model.put("cateList", categoryService.getCategoryListByActive());
		ModelAndView mv = new ModelAndView("listProduct", model);
		return mv;
	}

	@RequestMapping(value = "/admin/listProduct", method = RequestMethod.GET)
	public ModelAndView showListProductPage() {
		Map<String, Object> model = new HashMap<String, Object>();
		List<Category> cateList = categoryService.getCategoryListByActive();
		List<ProductBean> productList = prepareListProductBean(productService
				.getProductList());
		model.put("productList", productList);
		model.put("cateList", cateList);
		ModelAndView mv = new ModelAndView("listProduct", model);
		return mv;
	}

	@RequestMapping(value = "/admin/getAddNews", method = RequestMethod.GET)
	public ModelAndView showAddNewsPage(
			@ModelAttribute("news") NewsBean newsBean) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("news", new NewsBean());
		ModelAndView mv = new ModelAndView("addNews", model);
		return mv;
	}

	@RequestMapping(value = "/admin/addNews", method = RequestMethod.POST)
	public ModelAndView addNews(@ModelAttribute("news") NewsBean newsBean,
			@RequestParam("newsimage") MultipartFile image) {
		ModelAndView mv = new ModelAndView();
		Album album = new Album();
		if (!image.isEmpty()) {
			try {
				String location = servletContext.getRealPath("/");
				if (processAddImage(image, location,
						Constants.NEWS_IMAGE_FOLDER)) {
					if (processSaveImage(image, Constants.NEWS, album)) {
						newsBean.setImage(image.getOriginalFilename());
						if (processAddNews(newsBean)) {
							mv = new ModelAndView("redirect:/admin/listNews");
						}
					}
				}
			} catch (Exception ex) {
				Map<String, String> message = new HashMap<String, String>();
				message.put("error", ex.getMessage());
				mv = new ModelAndView("redirect:/admin/getAddNews", message);
			}
		}
		return mv;
	}

	@RequestMapping(value = "/admin/getUpdateNews", method = RequestMethod.GET)
	public ModelAndView showUpdateNewsPage(
			@RequestParam("newsId") String newsId,
			@ModelAttribute("news") NewsBean newsBean) {
		newsBean = prepareNewsBean(newsId);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("news", newsBean);
		ModelAndView mv = new ModelAndView("updateNews", model);
		return mv;
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/deleteNews", method = RequestMethod.GET)
	public ModelAndView deleteNews(HttpServletRequest request,
			HttpServletResponse response) {
		int newsID = Integer.parseInt(request.getParameter("NewsID"));
		Map<String, Object> model = new HashMap<String, Object>();
		int deleteNews = newsService.deleteNews(newsID);
		List<NewsBean> newsList = prepareListNewsBean(newsService.getNewsList());
		;
		model.put("newsList", newsList);
		model.put("cateList", categoryService.getCategoryListByActive());
		ModelAndView mv = new ModelAndView("listNews", model);
		return mv;
	}

	@RequestMapping(value = "/admin/updateNews", method = RequestMethod.POST)
	public ModelAndView updateNews(@ModelAttribute("news") NewsBean newsBean,
			@RequestParam("newsimage") MultipartFile image) {
		ModelAndView mv = new ModelAndView();
		Album album = new Album();
		if (!image.isEmpty()) {
			try {
				String location = servletContext.getRealPath("/");
				if (processAddImage(image, location,
						Constants.NEWS_IMAGE_FOLDER)) {
					if (processSaveImage(image, Constants.NEWS, album)) {
						newsBean.setImage(image.getOriginalFilename());
						if (newsService.updateNews(prepareUpdateNews(newsBean))) {
							mv = new ModelAndView("redirect:/admin/listNews");
						}
					}
				}
			} catch (Exception ex) {
				Map<String, String> message = new HashMap<String, String>();
				message.put("error", ex.getMessage());
				mv = new ModelAndView("redirect:/admin/getUpdateNews", message);
			}
		} else {
			if (newsService.updateNews(prepareUpdateNews(newsBean))) {
				mv = new ModelAndView("redirect:/admin/listNews");
			} else {
				Map<String, String> message = new HashMap<String, String>();
				message.put("error", "fail");
				mv = new ModelAndView("redirect:/admin/getUpdateNews", message);
			}
		}
		return mv;
	}

	@RequestMapping(value = "/admin/listNews", method = RequestMethod.GET)
	public ModelAndView showListNewsPage() {
		Map<String, Object> model = new HashMap<String, Object>();
		List<NewsBean> newsList = prepareListNewsBean(newsService.getNewsList());
		String folder = "news-images";
		String location = servletContext.getRealPath("/");
		String foldername = location + File.separator + "resources"
				+ File.separator + folder;
		String fileName = "";
		File file = null;
		File folderFile = null;
		StoreImage storeImage = new StoreImage();
		for (NewsBean nBean : newsList) {
			try {
				fileName = nBean.getImage();
				file = new File(foldername + File.separator + fileName);
				folderFile = new File(foldername);
				if (!file.exists()) {
					if (!folderFile.exists()) {
						folderFile.mkdir();
					}
					storeImage = imageService.getImageByGroupBy(fileName,
							"NEWS");
					byte[] bFile = storeImage.getData();
					FileUtils.writeByteArrayToFile(file, bFile);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		model.put("newsList", newsList);
		ModelAndView mv = new ModelAndView("listNews", model);
		return mv;
	}

	@RequestMapping(value = "/admin/listAlbum", method = RequestMethod.GET)
	public ModelAndView showListAlbumPage() {

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("albumList", prepareAlbumList(albumService.getAlbumList()));
		ModelAndView mv = new ModelAndView("listAlbum", model);
		return mv;
	}

	@RequestMapping(value = "/admin/getAddAlbum", method = RequestMethod.GET)
	public ModelAndView showAddAlbumPage(
			@ModelAttribute("album") AlbumBean albumBean) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("album", new AlbumBean());
		ModelAndView mv = new ModelAndView("addAlbum", model);
		return mv;
	}

	@RequestMapping(value = "/admin/addAlbum", method = RequestMethod.POST)
	public ModelAndView addNewAlbum(@ModelAttribute("album") AlbumBean albumBean) {
		ModelAndView mv = new ModelAndView("redirect:/admin/listAlbum");
		if (!albumService.addAlbum(prepareAlbum(albumBean))) {
			mv = new ModelAndView("redirect:/admin/getAddAlbum");
		}
		return mv;
	}

	@RequestMapping(value = "/admin/getUpdateAlbum", method = RequestMethod.GET)
	public ModelAndView showUpdateAlbumPage(
			@RequestParam("albumId") String albumId,
			@ModelAttribute("album") AlbumBean albumBean) {
		albumBean = prepareAlbumBean(albumId);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("album", albumBean);
		ModelAndView mv = new ModelAndView("updateAlbum", model);
		return mv;
	}

	@RequestMapping(value = "/admin/updateAlbum", method = RequestMethod.POST)
	public ModelAndView updateAlbum(@ModelAttribute("album") AlbumBean albumBean) {
		ModelAndView mv = new ModelAndView("redirect:/admin/listAlbum");
		if (!albumService.updateAlbum(prepareUpdateAlbum(albumBean))) {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("album", albumBean);
			mv = new ModelAndView("redirect:/admin/getUpdateAlbum", model);
		}

		return mv;
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/deleteAlbum", method = RequestMethod.GET)
	public ModelAndView deleteAlbum(HttpServletRequest request,
			HttpServletResponse response) {
		int albumID = Integer.parseInt(request.getParameter("AlbumID"));
		Map<String, Object> model = new HashMap<String, Object>();
		Album album = albumService.getAlbum(albumID);
		List<StoreImage> imageList = imageService.getListImageByAlbumID(album);
		for (StoreImage image : imageList) {
			int deleteImageOfAlbum = imageService.deleteImage(image.getId());
		}
		int deleteAlbum = albumService.deleteAlbum(albumID);
		model.put("albumList", prepareAlbumList(albumService.getAlbumList()));
		ModelAndView mv = new ModelAndView("listAlbum", model);
		return mv;
	}

	@RequestMapping(value = "/admin/getAlbumList", method = RequestMethod.GET)
	public ModelAndView getAlbumList(HttpServletRequest request,
			HttpServletResponse response) {
		String strAlbumID = request.getParameter("albumID");
		int albumID = Integer.parseInt(strAlbumID);
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		Album album = albumService.getAlbum(albumID);
		imageList = prepareListSliderBean(album);
		String folder = "";
		try {
			folder = new String(album.getName().toLowerCase().getBytes(),
					"UTF-8");
		} catch (UnsupportedEncodingException e1) {

			e1.printStackTrace();
		}
		String location = servletContext.getRealPath("/");
		String foldername = location + File.separator + "resources"
				+ File.separator + folder + "-images";
		String fileName = "";
		File file = null;
		File folderFile = null;
		StoreImage storeImage = new StoreImage();
		for (StoreImage sImage : imageList) {
			try {
				fileName = sImage.getName();
				file = new File(foldername + File.separator + fileName);
				folderFile = new File(foldername);
				if (!file.exists()) {
					if (!folderFile.exists()) {
						folderFile.mkdir();
					}
					storeImage = imageService.getImageByGroupBy(fileName, album
							.getName().toUpperCase());
					byte[] bFile = storeImage.getData();
					FileUtils.writeByteArrayToFile(file, bFile);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		model.put("imageList", imageList);
		model.put("albumList", albumService.getAlbumListByActive());
		model.put("chooseAlbum", album);
		ModelAndView mv = new ModelAndView("listSlider", model);
		return mv;
	}

	@RequestMapping(value = "/admin/listSlider", method = RequestMethod.GET)
	public ModelAndView showListSliderPage(
			@ModelAttribute("slider") ImageBean imageBean) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<StoreImage> imageList = new ArrayList<StoreImage>();
		for (Album album : albumService.getAlbumListByActive()) {
			if (null != album.getIsDefault() && album.getIsDefault()) {
				imageList = prepareListSliderBean(album);
			}
		}
		String folder = "slider-images";
		String location = servletContext.getRealPath("/");
		String foldername = location + File.separator + "resources"
				+ File.separator + folder;
		String fileName = "";
		File file = null;
		File folderFile = null;
		StoreImage storeImage = new StoreImage();
		for (StoreImage sImage : imageList) {
			try {
				fileName = sImage.getName();
				file = new File(foldername + File.separator + fileName);
				folderFile = new File(foldername);
				if (!file.exists()) {
					if (!folderFile.exists()) {
						folderFile.mkdir();
					}
					storeImage = imageService.getImageByGroupBy(fileName,
							"SLIDER");
					byte[] bFile = storeImage.getData();
					FileUtils.writeByteArrayToFile(file, bFile);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		model.put("imageList", imageList);
		model.put("albumList", albumService.getAlbumListByActive());
		ModelAndView mv = new ModelAndView("listSlider", model);
		return mv;
	}

	@RequestMapping(value = "/admin/getAddSlider", method = RequestMethod.GET)
	public ModelAndView showAddSliderPage(
			@ModelAttribute("slider") ImageBean imageBean) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("albumList",
				prepareAlbumList(albumService.getAlbumListByActive()));
		ModelAndView mv = new ModelAndView("addSlider", model);
		return mv;
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/deleteImage", method = RequestMethod.GET)
	public ModelAndView deleteImage(HttpServletRequest request,
			HttpServletResponse response) {
		int imageID = Integer.parseInt(request.getParameter("ImageID"));
		Map<String, Object> model = new HashMap<String, Object>();
		StoreImage stimage = imageService.getImage(imageID);
		Album album = albumService.getAlbum(stimage.getAlbum().getId());
		int deleteImage = imageService.deleteImage(imageID);
		List<StoreImage> imageList = prepareListSliderBean(album);
		model.put("imageList", imageList);
		model.put("albumList", albumService.getAlbumListByActive());
		model.put("chooseAlbum", album);
		ModelAndView mv = new ModelAndView("listSlider", model);
		return mv;
	}

	private Album prepareUpdateAlbum(AlbumBean albumBean) {
		Album album = albumService.getAlbum(albumBean.getId());
		// album.setName(albumBean.getName());
		album.setDescription(albumBean.getDescription());
		album.setIsActive(albumBean.getIsActive());
		album.setProcessDate(Formater.dateToString(new Date()));
		album.setUser(userName);
		return album;
	}

	@RequestMapping(value = "/admin/addSlider", method = RequestMethod.POST)
	public ModelAndView addNewSlider(
			@ModelAttribute("slider") ImageBean imageBean,
			@RequestParam("sliderImage") MultipartFile image) {
		ModelAndView mv = new ModelAndView();
		Map<String, String> message = new HashMap<String, String>();
		Album album = new Album();
		album = albumService.getAlbum(imageBean.getAlbumID());
		if (null == album) {
			message.put("error", "Please select Album");
			mv = new ModelAndView("redirect:/admin/getAddSlider", message);
			return mv;
		}
		String albumname = album.getName().toUpperCase().toString().trim();
		String folderName = albumname.toLowerCase() + "-images";
		if (!image.isEmpty()) {
			try {
				String location = servletContext.getRealPath("/");
				if (processAddImage(image, location, folderName)) {
					if (processSaveImage(image, albumname, album)) {
						mv = new ModelAndView("redirect:/admin/listSlider");
					}
				}

			} catch (Exception ex) {
				message.put("error", ex.getMessage());
				mv = new ModelAndView("redirect:/admin/getAddSlider", message);
			}
		}
		return mv;
	}

	@RequestMapping(value = "/admin/getUpdateSlider", method = RequestMethod.GET)
	public ModelAndView showUpdateSliderPage(
			@RequestParam("imageId") String imageId,
			@ModelAttribute("slider") ImageBean imageBean) {
		imageBean = prepareImageBean(imageId);
		Map<String, Object> model = new HashMap<String, Object>();
		Album album = albumService.getAlbum(imageBean.getAlbumID());
		model.put("image", imageBean);
		model.put("albumList", albumService.getAlbumListByActive());
		model.put("chooseAlbum", album);
		ModelAndView mv = new ModelAndView("updateSlider", model);
		return mv;
	}

	@RequestMapping(value = "/admin/updateSlider", method = RequestMethod.POST)
	public ModelAndView updateSlider(
			@ModelAttribute("slider") ImageBean imageBean,
			@RequestParam("imageId") String imageId,
			@RequestParam("sliderImage") MultipartFile image) {
		ModelAndView mv = new ModelAndView();
		Album album = new Album();
		album = albumService.getAlbum(imageBean.getAlbumID());
		String albumname = album.getName().toUpperCase().toString().trim();
		String folderName = albumname.toLowerCase() + "-images";
		String location = servletContext.getRealPath("/");
		StoreImage storeImage = imageService
				.getImage(Integer.parseInt(imageId));
		String folderStoreOldImage = storeImage.getImageType().toLowerCase()
				.toString().trim()
				+ "-images";
		if (!image.isEmpty()) {
			try {
				if (processAddImage(image, location, folderName)) {
					if (processUpdateImage(image, albumname, album, storeImage)) {
						mv = new ModelAndView("redirect:/admin/listSlider");
					}
				}
			} catch (Exception ex) {
				Map<String, String> message = new HashMap<String, String>();
				message.put("error", ex.getMessage());
				mv = new ModelAndView(
						"redirect:/admin/getUpdateSlider?imageId=" + imageId
								+ "", message);
			}
		} else {
			try {
				File file = new File(location + File.separator + "resources"
						+ File.separator + folderStoreOldImage + File.separator
						+ storeImage.getName());
				if (processAddImageForUpdate(file, location, folderName)) {
					if (processUpdateImageForUpdate(file, albumname, album,
							storeImage)) {
						mv = new ModelAndView("redirect:/admin/listSlider");
					}
				}

			} catch (Exception ex) {
				Map<String, String> message = new HashMap<String, String>();
				message.put("error", "fail");
				mv = new ModelAndView(
						"redirect:/admin/getUpdateSlider?imageId=" + imageId
								+ "", message);
			}

		}
		return mv;
	}

	private AlbumBean prepareAlbumBean(String albumId) {
		AlbumBean albumBean = new AlbumBean();
		Album album = albumService.getAlbum(Integer.parseInt(albumId));
		if (null != album) {
			albumBean.setId(album.getId());
			albumBean.setName(album.getName());
			albumBean.setDescription(album.getDescription());
			albumBean.setIsActive(album.getIsActive());
		}
		return albumBean;
	}

	private List<CategoryBean> prepareCategoryList(List<Category> categoryList) {
		List<CategoryBean> categoryBeans = new ArrayList<CategoryBean>();
		for (Category category : categoryList) {
			CategoryBean bean = new CategoryBean();
			bean.setId(category.getId());
			bean.setName(category.getName());
			bean.setDescription(category.getDescription());
			bean.setProcessDate(category.getProcessDate());
			bean.setIsActive(category.getIsActive());
			bean.setUser(category.getUser());
			categoryBeans.add(bean);
		}
		return categoryBeans;
	}

	private Category prepareCategory(CategoryBean categoryBean) {
		Category category = new Category();
		category.setId(null);
		category.setName(categoryBean.getName());
		category.setDescription(categoryBean.getDescription());
		category.setIsActive(true);
		category.setProcessDate(Formater.dateToString(new Date()));
		category.setUser(userName);
		return category;
	}

	private List<AlbumBean> prepareAlbumList(List<Album> albumList) {
		List<AlbumBean> albumBean = new ArrayList<AlbumBean>();
		for (Album album : albumList) {
			AlbumBean bean = new AlbumBean();
			bean.setId(album.getId());
			bean.setName(album.getName());
			bean.setDescription(album.getDescription());
			bean.setProcessDate(album.getProcessDate());
			bean.setIsActive(album.getIsActive());
			bean.setUser(album.getUser());
			albumBean.add(bean);
		}
		return albumBean;
	}

	private Album prepareAlbum(AlbumBean albumBean) {
		Album album = new Album();
		album.setId(null);
		album.setName(albumBean.getName());
		album.setDescription(albumBean.getDescription());
		album.setIsActive(albumBean.getIsActive());
		album.setProcessDate(Formater.dateToString(new Date()));
		album.setUser(userName);
		return album;
	}

	private boolean processAddProduct(ProductBean productBean) {
		Product product = new Product();
		product.setId(null);
		product.setName(productBean.getName());
		product.setPrice(productBean.getPrice());
		product.setHotprice(productBean.getHotprice());
		product.setDescription(productBean.getDescription());
		product.setIsActive(true);
		product.setIsMain(productBean.getIsMainProduct());
		product.setImage(productBean.getImage());
		product.setCategoryId(categoryService.getCategory(productBean
				.getCategoryId()));
		product.setProcessDate(Formater.dateToString(new Date()));
		product.setUser(userName);

		return productService.addProduct(product);
	}

	private Product prepareUpdateProduct(ProductBean productBean) {
		Product product = productService.getProduct(productBean.getId());
		product.setName(productBean.getName());
		product.setDescription(productBean.getDescription());
		product.setPrice(productBean.getPrice());
		product.setIsActive(productBean.getIsActive());
		product.setIsMain(productBean.getIsMainProduct());
		product.setCategoryId(categoryService.getCategory(productBean
				.getCategoryId()));
		product.setProcessDate(Formater.dateToString(new Date()));
		product.setUser(userName);

		return product;
	}

	private boolean processAddImage(MultipartFile image, String location,
			String folder) throws Exception {
		return FileUpload.saveImage(location, image, folder);
	}

	private boolean processAddImageForUpdate(File imageFile, String location,
			String folder) throws Exception {
		return FileUpload.saveImageForUpdate(location, imageFile, folder);
	}

	private boolean processSaveImage(MultipartFile file, String imageType,
			Album album) throws Exception {
		StoreImage image = new StoreImage();
		image.setId(null);
		image.setName(file.getOriginalFilename());
		image.setData(file.getBytes());
		image.setImageType(imageType);
		image.setIsShow(true);
		if (null != album.getId()) {
			image.setAlbum(album);
		}
		return imageService.addImage(image);
	}

	private boolean processUpdateImage(MultipartFile file, String imageType,
			Album album, StoreImage image) throws Exception {
		image.setName(file.getOriginalFilename());
		image.setData(file.getBytes());
		image.setImageType(imageType);
		if (null != album.getId()) {
			image.setAlbum(album);
		}
		return imageService.updateImage(image);
	}

	private boolean processUpdateImageForUpdate(File file, String imageType,
			Album album, StoreImage image) throws Exception {
		// FileInputStream fis = null;
		byte[] bfile = new byte[(int) file.length()];
		image.setName(file.getName());
		image.setData(bfile);
		image.setImageType(imageType);
		if (null != album.getId()) {
			image.setAlbum(album);
		}
		return imageService.updateImage(image);
	}

	private boolean processChangePassword(AccountBean accountBean) {
		User user = userService.getUser(userName);
		if (accountBean.getNewPass().equals(accountBean.getConfirmPass())) {
			if (MD5.crypt(accountBean.getOldPass()).equals(user.getPassword())) {
				user.setPassword(MD5.crypt(accountBean.getNewPass()));
				return userService.updateUser(user);
			}
		}
		return false;
	}

	private CategoryBean prepareCategoryBean(String cateId) {
		CategoryBean categoryBean = new CategoryBean();
		Category category = categoryService.getCategory(Integer
				.parseInt(cateId));
		if (null != category) {
			categoryBean.setId(category.getId());
			categoryBean.setName(category.getName());
			categoryBean.setDescription(category.getDescription());
			categoryBean.setIsActive(category.getIsActive());
		}
		return categoryBean;
	}

	private Category prepareUpdateCategory(CategoryBean categoryBean) {
		Category category = categoryService.getCategory(categoryBean.getId());
		category.setName(categoryBean.getName());
		category.setDescription(categoryBean.getDescription());
		category.setIsActive(categoryBean.getIsActive());
		category.setProcessDate(Formater.dateToString(new Date()));
		category.setUser(userName);
		return category;
	}

	private List<ProductBean> prepareListProductBean(List<Product> productList) {
		List<ProductBean> list = new ArrayList<ProductBean>();
		for (Product p : productList) {
			ProductBean b = new ProductBean();
			b.setId(p.getId());
			b.setName(p.getName());
			b.setPrice(p.getPrice());
			b.setDescription(p.getDescription());
			b.setProcessDate(p.getProcessDate());
			b.setUser(p.getUser());
			b.setIsActive(p.getIsActive());
			b.setImage(p.getImage());
			b.setIsMainProduct(p.getIsMain());
			b.setCategoryId(p.getCategoryId().getId());
			list.add(b);
		}
		return list;
	}

	private ProductBean prepareProductBean(String productId) {
		ProductBean productBean = new ProductBean();
		Product product = productService
				.getProduct(Integer.parseInt(productId));
		if (null != product) {
			productBean.setId(product.getId());
			productBean.setName(product.getName());
			productBean.setPrice(product.getPrice());
			productBean.setDescription(product.getDescription());
			productBean.setImage(product.getImage());
			productBean.setProcessDate(product.getProcessDate());
			productBean.setUser(product.getUser());
			productBean.setIsActive(product.getIsActive());
			productBean.setIsMainProduct(product.getIsMain());
			productBean.setCategoryId(product.getCategoryId().getId());
		}
		return productBean;
	}

	private boolean processAddNews(NewsBean newsBean) {
		News news = new News();
		news.setId(null);
		news.setName(newsBean.getName());
		news.setIsActive(newsBean.getIsActive());
		try {
			news.setFulldescen(newsBean.getFulldescen().getBytes("UTF-8"));
			news.setFulldescvi(newsBean.getFulldescvi().getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		news.setShortdescen(newsBean.getShortdescen());
		news.setShortdescvi(newsBean.getShortdescvi());
		news.setImage(newsBean.getImage());
		news.setProcessDate(Formater.dateToString(new Date()));
		news.setUser(userName);

		return newsService.addNews(news);
	}

	private NewsBean prepareNewsBean(String newsId) {
		NewsBean newsBean = new NewsBean();
		News news = newsService.getNews(Integer.parseInt(newsId));
		if (null != news) {
			newsBean.setId(news.getId());
			newsBean.setName(news.getName());
			try {
				newsBean.setFulldescen(new String(news.getFulldescen(), "UTF-8"));
				newsBean.setFulldescvi(new String(news.getFulldescvi(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			newsBean.setShortdescen(news.getShortdescen());
			newsBean.setShortdescvi(news.getShortdescvi());
			newsBean.setImage(news.getImage());
			newsBean.setProcessDate(news.getProcessDate());
			newsBean.setUser(news.getUser());
			newsBean.setIsActive(news.getIsActive());
		}
		return newsBean;
	}

	private List<NewsBean> prepareListNewsBean(List<News> newsList) {
		List<NewsBean> list = new ArrayList<NewsBean>();
		for (News n : newsList) {
			NewsBean b = new NewsBean();
			b.setId(n.getId());
			b.setName(n.getName());
			b.setShortdescen(n.getShortdescen());
			b.setShortdescvi(n.getShortdescvi());
			b.setProcessDate(n.getProcessDate());
			b.setUser(n.getUser());
			b.setIsActive(n.getIsActive());
			b.setImage(n.getImage());
			list.add(b);
		}
		return list;
	}

	private News prepareUpdateNews(NewsBean newsBean) {
		News news = newsService.getNews(newsBean.getId());
		news.setName(newsBean.getName());
		news.setIsActive(newsBean.getIsActive());
		try {
			news.setFulldescen(newsBean.getFulldescen().getBytes("UTF-8"));
			news.setFulldescvi(newsBean.getFulldescvi().getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		news.setShortdescen(newsBean.getShortdescen());
		news.setShortdescvi(newsBean.getShortdescvi());
		if (null != newsBean.getImage() && !("").equals(newsBean.getImage())) {
			news.setImage(newsBean.getImage());
		}
		news.setProcessDate(Formater.dateToString(new Date()));
		news.setUser(userName);

		return news;
	}

	private List<StoreImage> prepareListSliderBean(Album album) {
		// List<AlbumBean> list = new ArrayList<AlbumBean>();
		List<StoreImage> images = new ArrayList<StoreImage>();
		images = imageService.getListImageByAlbumID(album);

		return images;
	}

	private ImageBean prepareImageBean(String imageId) {
		ImageBean imageBean = new ImageBean();
		StoreImage storeImage = imageService
				.getImage(Integer.parseInt(imageId));
		if (null != storeImage) {
			imageBean.setId(storeImage.getId());
			imageBean.setName(storeImage.getName());
			imageBean.setAlbumID(storeImage.getAlbum().getId());
			imageBean.setImageType(storeImage.getImageType());
		}
		return imageBean;
	}

	private List<Product> prepareLisProductBean(Category cate) {
		List<Product> products = new ArrayList<Product>();
		products = productService.getProductListByCate(cate);
		return products;
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/hideImage", method = RequestMethod.POST)
	public @ResponseBody
	void hideImage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int imageID = Integer.parseInt(request.getParameter("ImageID"));
		int hide = imageService.hideImage(imageID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/unhideImage", method = RequestMethod.POST)
	public @ResponseBody
	void unhideImage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int imageID = Integer.parseInt(request.getParameter("ImageID"));
		int unhide = imageService.unhideImage(imageID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/hideProduct", method = RequestMethod.POST)
	public @ResponseBody
	void hideProduct(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int productID = Integer.parseInt(request.getParameter("ProductID"));
		int hide = productService.hideProduct(productID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/unhideProduct", method = RequestMethod.POST)
	public @ResponseBody
	void unhideProduct(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int productID = Integer.parseInt(request.getParameter("ProductID"));
		int hide = productService.unhideProduct(productID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/hideNews", method = RequestMethod.POST)
	public @ResponseBody
	void hideNews(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int newsID = Integer.parseInt(request.getParameter("NewsID"));
		int hide = newsService.hideNews(newsID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/unhideNews", method = RequestMethod.POST)
	public @ResponseBody
	void unhideNews(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int newsID = Integer.parseInt(request.getParameter("NewsID"));
		int hide = newsService.unhideNews(newsID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/hideCategory", method = RequestMethod.POST)
	public @ResponseBody
	void hideCategory(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int cateID = Integer.parseInt(request.getParameter("CategoryID"));
		Category category = categoryService.getCategory(cateID);
		List<Product> productList = productService
				.getProductListByCate(category);
		for (Product product : productList) {
			int hideProduct = productService.hideProduct(product.getId());
		}
		int hide = categoryService.hideCategory(cateID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/unhideCategory", method = RequestMethod.POST)
	public @ResponseBody
	void unhideCategory(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int cateID = Integer.parseInt(request.getParameter("CategoryID"));
		Category category = categoryService.getCategory(cateID);
		List<Product> productList = productService
				.getProductListByCate(category);
		for (Product product : productList) {
			int hideProduct = productService.unhideProduct(product.getId());
		}
		int hide = categoryService.unhideCategory(cateID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/hideAlbum", method = RequestMethod.POST)
	public @ResponseBody
	void hideAlbum(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int albumID = Integer.parseInt(request.getParameter("AlbumID"));
		Album album = albumService.getAlbum(albumID);
		List<StoreImage> imageList = imageService.getListImageByAlbumID(album);
		for (StoreImage image : imageList) {
			int hideImage = imageService.hideImage(image.getId());
		}
		int hide = albumService.hideAlbum(albumID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/admin/unhideAlbum", method = RequestMethod.POST)
	public @ResponseBody
	void unhideAlbum(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int albumID = Integer.parseInt(request.getParameter("AlbumID"));
		Album album = albumService.getAlbum(albumID);
		List<StoreImage> imageList = imageService.getListImageByAlbumID(album);
		for (StoreImage image : imageList) {
			int hideImage = imageService.unhideImage(image.getId());
		}
		int hide = albumService.unhideAlbum(albumID);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		response.getWriter().write("success");

	}

}
